<?php

use GatewayWorker\BusinessWorker;
use GatewayWorker\Gateway;
use GatewayWorker\Register;
use Workerman\Worker;

/**
 * 去除左右两边符号
 * @param string $string
 * @param string|array $charList
 * @return string
 */
function trimList($string = '',$charList = '')
{
    if(is_array($charList)) {
        foreach ($charList as $v) {
            $string = trim($string,$v);
        }
    }elseif (is_string($charList)) {
        $string = trim($string,$charList);
    }
    return $string;
}

/**
 * 转换数组
 * @param $data
 * @return mixed
 */
function toArray($data)
{
    return json_decode(json_encode($data),true);
}

/**
 * json字符串转数组
 * @param string $str
 * @return mixed
 */
function jsonToArray($str = '')
{
    return json_decode($str,true);
}

/**
 * 转换成json字符串
 * @param array|object|string|callable|int $data
 * @return false|string
 */
function toJson($data)
{
    return json_encode($data);
}

function startBusinessWorker()
{
    $workmanConfig = require_once(__DIR__ . '/../../config/workman.php');
    $BusinessWorker = $workmanConfig['BusinessWorker'];
    $worker = new BusinessWorker();
    $worker->name = $BusinessWorker['name'];
    $worker->count = $BusinessWorker['count'];
    $worker->registerAddress = "{$BusinessWorker['ip']}:{$BusinessWorker['port']}";
    $worker->eventHandler = \App\Workerman\Events::class;
    // 如果不是在根目录启动，则运行runAll方法
    if (!defined('GLOBAL_START')) {
        Worker::runAll();
    }
}

function startGateWay()
{
    $workmanConfig = require_once(__DIR__ . '/../../config/workman.php');
    $BusinessWorker = $workmanConfig['BusinessWorker'];
    $Gateway = $workmanConfig['Gateway'];
    // gateway 进程，这里使用Text协议，可以用telnet测试
    $gateway = new Gateway("websocket://{$Gateway['ip']}:{$Gateway['port']}");
    // gateway名称，status方便查看
    $gateway->name = $Gateway['name'];
    // gateway进程数
    $gateway->count = $Gateway['count'];
    // 本机ip，分布式部署时使用内网ip
    $gateway->lanIp = $Gateway['lanIp'];
    // 内部通讯起始端口，假如$gateway->count=4，起始端口为4000
    // 则一般会使用4000 4001 4002 4003 4个端口作为内部通讯端口
    $gateway->startPort = $Gateway['startPort'];
    // 服务注册地址
    $gateway->registerAddress = "{$BusinessWorker['ip']}:{$BusinessWorker['port']}";
    $gateway->disableInput = $Gateway['disableInput'];
    // 心跳间隔
    $gateway->pingInterval = $Gateway['pingInterval'];
    // 心跳数据
    $gateway->pingData = $Gateway['pingData'];
    if (!defined('GLOBAL_START')) {
        Worker::runAll();
    }
}

function startRegister()
{
    $workmanConfig = require_once(__DIR__ . '/../../config/workman.php');
    $Register = $workmanConfig['Register'];
    // register 必须是text协议
    new Register("text://{$Register['ip']}:{$Register['port']}");
    if (!defined('GLOBAL_START')) {
        Worker::runAll();
    }
}
